﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using PairingMatrix.Common.Enum;
using PairingMatrix.ViewModel;
using System.Linq;

namespace PairingMatrix.View.Behavior
{
    public class CalculatePairPositionsBehavior : Behavior<TeamMemberCardControl>
    {
        private TeamMemberCardViewModel _teamMemberCardViewModel;

        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
            {
                _teamMemberCardViewModel = (TeamMemberCardViewModel)AssociatedObject.DataContext;
                _teamMemberCardViewModel.PairedWith.CollectionChanged += PairedWith_CollectionChanged;
                _teamMemberCardViewModel.ProjectCardAssignments.CollectionChanged += ProjectCardAssignments_CollectionChanged;
            };
        }

        private void ProjectCardAssignments_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            CalculateProjectAssignmentsPositions();
        }

        void PairedWith_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            CalculatePairPositions();
        }

        private void CalculateProjectAssignmentsPositions()
        {
            var assignments = _teamMemberCardViewModel.ProjectCardAssignments.ToList();
            for (int i = 0; i < assignments.Count; i++)
            {
                var viewModel = assignments[i];
                viewModel.Position = new Point(150, (i + 1) * 30 + 100);
            }
            
        }

        private void CalculatePairPositions()
        {
            var pairedWith = _teamMemberCardViewModel.PairedWith.ToList();
            pairedWith.Sort();
            for (int i = 0; i < pairedWith.Count ; i++)
            {
                var viewModel = pairedWith[i];
                viewModel.Position = new Point(-2000,-2000);
            }

            for (int i = 0; i < (pairedWith.Count >= 3 ? 3 : pairedWith.Count); i++)
            {
                var viewModel = pairedWith[i];
                viewModel.Position = new Point((i + 1) * 100 + 50, -120);
            }
            
            for (int i = pairedWith.Count - 1; i >= (pairedWith.Count >= 6 ? pairedWith.Count - 3 : 3); i--)
            {
                var viewModel = pairedWith[i];
                viewModel.Position = new Point((pairedWith.Count - i) * 100 + 50, 0);
            }
        }
    }
}
